import os
import pymysql
from pymysql.cursors import DictCursor
import logging
from config.config import *
from apiException.custom_exception import DataBaseException, GetDataException, ExecuteSqlException
from utils.decorator  import singleton


# 实现单列模式的装饰器
# def singleton(cls):
#     instance = {}
#
#     def get_instance(*args, **kwargs):
#         if cls not in instance:
#             instance[cls] = cls(*args, **kwargs)
#         return instance[cls]
#     return get_instance


@singleton
class DataBase:

    def __init__(self):
        # 只在类的内部访问db，设置为私有的
        self.__db = self.__getConnet()


    # 创建连接对象的方法，游标对象的方法
    @staticmethod
    def __getConnet():

        # __data = GetConfig().get_database_data()
        __data = eval(os.environ["DATABASE"])
        try:
            conn = pymysql.Connect(
                # host=DB_HOST,
                # port=DB_PORT,
                # user=DB_USER,
                # passwd=DB_PASSWORD,
                # database=DB_NAME,
                # charset=CHARSET,
                # autocommit=AUTOCOMMIT
                **__data,
            )
            return conn


        except Exception as e:
            logging.error(f"数据库连接识别，错误异常是：{e}")
            raise DataBaseException()

        # 创建游标
        # with conn.cursor(DictCursor) as cur:
        #     return cur

    # 执行sql，不需要返回值-删除，修改
    def get_one(self, sql):
        try:
            if self.__db:
                with self.__db.cursor(DictCursor) as cur:
                    cur.execute(sql)
                    return cur.fetchone()
        except Exception as e:
            logging.error(f"数据库查询失败，错误异常是：{e}")
            raise GetDataException()

    # 执行sql，不需要返回值--查询
    def execute_sql(self, *sqls):
        try:
            if self.__db:
                with self.__db.cursor(DictCursor) as cur:
                    for sql in sqls:
                        cur.execute(sql)
        except Exception as e:
            logging.error(f"数据库修改/删除异常，错误异常是：{e}")
            raise ExecuteSqlException()
